package com.template_engine.directive;

import com.template_engine.constant.DirectiveConstant;
import com.template_engine.domain.ApplicationContext;
import com.template_engine.utils.FileUtils;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import java.io.IOException;
import java.io.Writer;

/**
 * 当在脚本中执行#error "错误消息" 会停止渲染
 * @author shenguangyang
 * @date 2021-11-13 7:34
 */
public class Error extends Directive {

    @Override
    public String getName() {
        //指令名称，也就是在模板中使用的指令名字
        return DirectiveConstant.ERROR_NAME;
    }

    /**
     * getType:当前有LINE,BLOCK两个值，line行指令，不要end结束符，block块指令，需要end结束符
     */
    @Override
    public int getType() {
        return LINE;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        String templateName = context.getCurrentTemplateName();
        String errorMessage = "";
        if (node.jjtGetNumChildren() != 0) {
            Node node1 = node.jjtGetChild(0);
            if (node1 != null) {
                errorMessage = node1.literal();
            }
        }
        System.err.println("templateName: " + templateName + ", line: " + node.getLine() + ", error: " + ("".equals(errorMessage) ? "exit" : errorMessage));
        System.exit(0);
        return false;
    }
}
